﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class SpriteManager : MonoBehaviour
{
    public static GameObject m_pMainObject;
    private static SpriteManager _instance = null;
    public Dictionary<string, Object[]> m_pAtlasDic;//图集的集合
    public static SpriteManager getInstance()
    {
        if(_instance == null)
        {
            _instance = m_pMainObject.GetComponent<SpriteManager>();
        }
        return _instance;
    }
    private void Awake()
    {
        initData();
    }
    private void initData()
    {
        SpriteManager.m_pMainObject = gameObject;
        m_pAtlasDic = new Dictionary<string, Object[]>();
    }
    // 从字典加载一个图片，如果没有就去资源里面找
    public Sprite LoadAtlasSprite(string _spriteAtlasPath, string _spriteName)
    {
        Sprite _sprite = FindSpriteFromBuffer(_spriteAtlasPath, _spriteName);
        if (_sprite == null)
        {
            //Debug.Log("sprite not found" + "_spriteAtlasPath: " + _spriteAtlasPath + "  spriteName:" + _spriteName);
            Object[] _atlas = Resources.LoadAll(_spriteAtlasPath);
            //Debug.Log("atlas的长度：" + _atlas.Length);
            if (_atlas == null) Debug.Log(_spriteAtlasPath + "not exists");
            m_pAtlasDic.Add(_spriteAtlasPath, _atlas);
            _sprite = SpriteFromAtlas(_atlas, _spriteName);

        }
        //else Debug.Log("_spriteAtlasPath: " + _spriteAtlasPath + "  spriteName:" + _spriteName);
        return _sprite;
    }
    //从缓存中查找图集，并找到sprite
    private Sprite FindSpriteFromBuffer(string _spriteAtlasPath, string _spriteName)
    {
        if (m_pAtlasDic.ContainsKey(_spriteAtlasPath))
        {
            Object[] _atlas = m_pAtlasDic[_spriteAtlasPath];
            if (_atlas == null) Debug.Log(_spriteAtlasPath + "do not exists");
            Sprite _sprite = SpriteFromAtlas(_atlas, _spriteName);
            return _sprite;
        }
        return null;
    }
    //从图集中，并找出sprite
    private Sprite SpriteFromAtlas(Object[] _atlas, string _spriteName)
    {
        for(int i = 0; i < _atlas.Length; i++)
        {
            if(_atlas[i].GetType() == typeof(UnityEngine.Sprite))
            {
                if(_atlas[i].name == _spriteName)
                {
                    //Debug.Log(_atlas[i].name);
                    return (Sprite)_atlas[i];
                }
            }
        }
        return null;
    }
    // Start is called before the first frame update
    void Start()
    {
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}
